﻿using System;
using System.Collections.Generic;
using System.Data;
using viForum.Classes;
using viForum.Providers;
using visinia.SmartEngine.Cache;

namespace viForum.Controllers
{
    public class CategoryController
    {
        public static void AddCategory(Category category)
        {
            viForumDataProvider.Provider.AddCategory(category.Title);
            DataCache.DeleteCacheMultiple("vf_cate");
        }

        public static void UpdateCategory(Category category)
        {
            viForumDataProvider.Provider.UpdateCategory(category.CategoryId, category.Title);
            DataCache.DeleteCacheMultiple("vf_cate");
        }

        public static void DeleteCategory(Category category)
        {
            viForumDataProvider.Provider.DeleteCategory(category.CategoryId);
            DataCache.DeleteCacheMultiple("vf_cate");
        }

        #region CACHE KEYS
        private const string KEY_ALL_CATEGORIES = "vf_categories";
        #endregion

        public static List<Category> GetCategories()
        {
            List<Category> categories = (List<Category>)DataCache.GetCache(KEY_ALL_CATEGORIES);
            if (categories == null)
            {
                categories = FillCategories(viForumDataProvider.Provider.GetCategories());
                DataCache.SetCache(KEY_ALL_CATEGORIES, categories);
            }
            return categories;
        }

        public static Category GetCategory(int CategoryId)
        {
            return GetCategories().Find(p => p.CategoryId == CategoryId);
        }

        #region HELPERS
        private static List<Category> FillCategories(IDataReader dr)
        {
            List<Category> list = new List<Category>();
            while (dr.Read())
            {
                list.Add(ActualRead(dr));
            }
            dr.Close();
            return list;
        }
        private static Category ActualRead(IDataReader dr)
        {
            Category category = new Category();
            if (dr["CategoryId"] != Convert.DBNull)
                category.CategoryId = (int)dr["CategoryId"];
            if (dr["Title"] != Convert.DBNull)
                category.Title = (string)dr["Title"];
            return category;
        }
        #endregion
    }
}
